package com.tokudu.demo;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class ContextContentProvider extends ContentProvider {
	private SQLiteOpenHelper mOpenHelper;
	private static final int ITEMS = 1;
	private static final int ITEM_ID = 2;
	private static final UriMatcher sURLMatcher = new UriMatcher(
			UriMatcher.NO_MATCH);
	public static final Uri CONTENT_URI = Uri
			.parse("content://com.tokudu.demo.context/context");
	static {
		sURLMatcher.addURI("com.tokudu.demo.context", "context", ITEMS);
		sURLMatcher.addURI("com.tokudu.demo.context", "context/#", ITEM_ID);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		//private static final String HISTORY_DATABASE = "context";

		private static final int VERSION = 1;

		public DatabaseHelper(Context context) {
			super(context, "context", null, VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			String sql = "CREATE TABLE context(_id INTEGER PRIMARY KEY,msgid varchar(32),topic varchar(32),remote varchar(32),self varchar(32),message varchar(8000),isout int,static int);"
					+ "CREATE INDEX context_index_0 ON context(topic,remote,self);"
					+ "CREATE INDEX context_index_1 ON context(remotephone,topic);"
					+ "CREATE INDEX context_index_2 ON context(remotephone);";
			db.execSQL(sql);

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

			String sql = "DROP TABLE IF EXIST context;"
					+ "DROP INDEX IF EXIST context_index_0;"
					+ "DROP INDEX IF EXIST context_index_1;"
					+ "DROP INDEX IF EXIST context_index_2;";
			db.execSQL(sql);
			onCreate(db);

		}

	}

	@Override
	public int delete(Uri url, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		
		switch (sURLMatcher.match(url)) {
		case ITEMS:
			count = db.delete("context", where, whereArgs);
			break;
		case ITEM_ID:
			String segment = url.getPathSegments().get(1);
			//long rowId = Long.parseLong(segment);
			if (TextUtils.isEmpty(where)) {
				where = "_id=" + segment;
			} else {
				where = "_id=" + segment + " AND (" + where + ")";
			}
			count = db.delete("context", where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Cannot delete from URL: " + url);
		}
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	@Override
	public String getType(Uri url) {
		int match = sURLMatcher.match(url);
		switch (match) {
		case ITEMS:
			return "vnd.android.cursor.dir/alarms";
		case ITEM_ID:
			return "vnd.android.cursor.item/alarms";
		default:
			throw new IllegalArgumentException("Unknown URL");

		}
	}

	@Override
	public Uri insert(Uri url, ContentValues initialValues) {
		if (sURLMatcher.match(url) != ITEMS) {
			throw new IllegalArgumentException("Cannot insert into URL: " + url);
		}
		ContentValues values;
		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = db.insert("context", null, values);
		if (rowId < 0) {
			throw new SQLException("Failed to insert row into " + url);
		}
		Uri newUrl = ContentUris.withAppendedId(CONTENT_URI, rowId);
		getContext().getContentResolver().notifyChange(newUrl, null);
		return newUrl;

	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;

	}

	@Override
	public Cursor query(Uri url, String[] projection, String where,
	String[] whereArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		int match = sURLMatcher.match(url);
		switch (match) {

		case ITEMS:
			qb.setTables("context");
			break;

		case ITEM_ID:
			qb.setTables("context");
			qb.appendWhere("_id=");
			qb.appendWhere(url.getPathSegments().get(1));
			break;
		default:

			throw new IllegalArgumentException("Unknown URL " + url);

		}
		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor cur = qb.query(db, projection, where, whereArgs, null, null,
				sortOrder);
		if (cur != null) {
			cur.setNotificationUri(getContext().getContentResolver(), url);
		}
		return cur;
	}

	@Override
	public int update(Uri url, ContentValues values, String where,
			String[] whereArgs) {
		int count;
		long rowId = 0;
		int match = sURLMatcher.match(url);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		switch (match) {
		case ITEM_ID: {
			String segment = url.getPathSegments().get(1);
			rowId = Long.parseLong(segment);
			count = db.update("context", values, "_id=" + rowId, null);
			break;
		}
		case ITEMS: {
			count = db.update("context", values, where, whereArgs);
			break;
		}
		default: {
			throw new UnsupportedOperationException("Cannot update URL: " + url);
		}
		}
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

}
